package wangxiaotao.utils;


import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * minio工具类
 */
public class MinioUtils {

    /**
     * 判断桶是否存在
     * @param bucketName
     * @return
     */
    public static boolean bucketExists(String bucketName) {
        try {
            return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 新建桶
     *
     * @param bucketName
     * @return
     */
    public static boolean makeBucket(String bucketName) {
        try {
            List<Bucket> buckets = minioClient.listBuckets();
            for (Bucket bucket : buckets){
                if (bucket.name().equals(bucketName))
                    throw new MinioException("桶已经存在");
            }
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 列出桶里所有对象的名称 prefix筛选
     * @param bucketName
     * @param prefix
     * @return
     */
    public static List<String> listObjectByBucket(String bucketName,String ...prefix) {
        List<String> list = new ArrayList<>();
        if (bucketExists(bucketName)) {
            String relPrefix = String.join("/", prefix);
            Iterable<Result<Item>> results = minioClient
                    .listObjects(ListObjectsArgs
                            .builder()
                            .bucket(bucketName)
                            .recursive(true)
                            .prefix(relPrefix)
                            .build());
            for (Result<Item> res : results){
                Item item = null;
                try {
                    item = res.get();
                    list.add(item.objectName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    /**
     * 本地文件上传文件到bucket
     *
     * @param bucketName
     * @param objectName
     * @param fileName
     * @return
     */
    public static boolean uploadObjectByBucket(String bucketName, String objectName, String fileName) {
        if (bucketExists(bucketName)) {
            try {
                minioClient.uploadObject(
                        UploadObjectArgs.builder()
                                .bucket(bucketName)
                                .filename(fileName)//路径
                                .object(objectName)//名称
                                .build()
                );
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 文件上传
     * @param bucketName
     * @param file
     * @return 文件名称
     */
    public static String uploadObjectByBucket(String bucketName, MultipartFile file) {
        String fileNameFormat = fileNameFormat(Objects.requireNonNull(file.getOriginalFilename()));
        if (bucketExists(bucketName)) {
            if (bucketExists(bucketName)) {
                upload(bucketName,fileNameFormat,file);
            }
        }
        return fileNameFormat;
    }

    public static String uploadObjectByBucket(String bucketName,String prefix, MultipartFile file) {
        String realFileName = prefix+"/"+fileNameFormat(Objects.requireNonNull(file.getOriginalFilename()));
        if (bucketExists(bucketName)) {
            upload(bucketName,realFileName,file);
        }
        return realFileName;
    }

    /**
     * 指定路径 文件上传
     * @param bucketName
     * @param file
     * @param path 路径
     * @return
     */
    public static String[] uploadObjectBatchByBucket(String bucketName,String prefixName, MultipartFile[] file,String ...path){
        String [] resultPath = new String[file.length];
        if (bucketExists(bucketName)){
            try {
                for (int i = 0; i < file.length; i++) {
                    if (path.length!=0)
                        resultPath[i] = String.join("/", path)+"/"+prefixName+"_"+fileNameFormat(Objects.requireNonNull(file[i].getOriginalFilename()));
                    else
                        resultPath[i] = prefixName+"_"+fileNameFormat(Objects.requireNonNull(file[i].getOriginalFilename()));
                    minioClient.putObject(
                            PutObjectArgs.builder()
                                    .bucket(bucketName)
                                    .stream(file[i].getInputStream(), file[i].getSize(), -1)
                                    .object(resultPath[i])
                                    .contentType(file[i].getContentType())
                                    .build());
                }
                return resultPath;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 下载文件到本地
     * @param bucketName
     * @param objectName
     * @param fileName
     * @return
     */
    public static boolean downloadObjectByName(String bucketName, String objectName, String fileName) {
        if (bucketExists(bucketName)){
            try {
                minioClient.downloadObject(
                        DownloadObjectArgs.builder()
                                .bucket(bucketName)
                                .filename(fileName)
                                .object(objectName)
                                .build()
                );
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 判断文件是否存在
     * @param bucketName
     * @param objectName
     * @return true存在 false不存在
     */
    public static boolean stateObject(String bucketName, String objectName) {
        if(bucketExists(bucketName)){
            try {
                minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    /**
     * 获取文件流对象
     * @param bucketName
     * @param objectName
     * @return
     */
    public static InputStream getObjectByName(String bucketName, String objectName){
        if(bucketExists(bucketName)){
            try {
                GetObjectResponse object = minioClient.getObject(GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build());

                return object;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 在桶里删除一个object
     * @param bucketName
     * @param objectName
     * @return true为删除成功
     */
    public static boolean removeObjectByBucketName(String bucketName,String objectName){
        if (bucketExists(bucketName)){
            try {
                minioClient.removeObject(
                        RemoveObjectArgs.builder()
                                .bucket(bucketName)
                                .object(objectName)
                                .build()
                );
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 文件大小显示单位处理
     * @param size
     * @return
     */
    private static String sizeDo(Long size){
        if (size<1024){
            return size+"B";
        } else if (size <1024000){//1000kb
            return size/1024+"KB";
        }else if (size <1024000000) {//1000mb
            return size/1024000+"MB";
        }else
            return size/1024000000+"GB";
    }

    /**
     * 文件名称处理 加上时间戳
     * @param fileName
     * @return
     */
    public static String fileNameFormat(String fileName){
        String res = fileName;
        if (fileName.length()>10)
            res = fileName.substring(fileName.length()-10);
        return new SimpleDateFormat("MMddHHmmss").format(new Date())+res;
    }

    public static void upload(String bucketName,String objectName,MultipartFile file){
        try {
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .stream(file.getInputStream(),file.getSize(),-1)
                            .object(objectName)
                            .build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final MinioClient minioClient = (MinioClient) SpringUtils.getBean("minioClient");
}
